package com.zxing.practice.config;

import com.mybatisflex.core.query.QueryWrapper;
import com.zxing.practice.entity.system.SysRoleEntity;
import com.zxing.practice.entity.system.SysUserEntity;
import com.zxing.practice.entity.system.table.SysRoleEntityTableDef;
import com.zxing.practice.entity.system.table.SysUserEntityTableDef;
import com.zxing.practice.entity.system.table.SysUserRoleEntityTableDef;
import com.zxing.practice.mapper.system.SysRoleMapper;
import com.zxing.practice.mapper.system.SysUserMapper;
import com.zxing.practice.config.vo.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private SysRoleMapper roleMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper userQuery = QueryWrapper.create()
                .where(SysUserEntityTableDef.SYS_USER_ENTITY.UNAME.eq(username));
        SysUserEntity sysUser = userMapper.selectOneByQuery(userQuery);
        Integer id = sysUser.getId();
        QueryWrapper roleQuery = QueryWrapper.create()
                .from(SysUserEntityTableDef.SYS_USER_ENTITY)
                .join(SysUserRoleEntityTableDef.SYS_USER_ROLE_ENTITY).on(SysUserEntityTableDef.SYS_USER_ENTITY.ID.eq(SysUserRoleEntityTableDef.SYS_USER_ROLE_ENTITY.USER_ID))
                .join(SysRoleEntityTableDef.SYS_ROLE_ENTITY).on(SysUserRoleEntityTableDef.SYS_USER_ROLE_ENTITY.ROLE_ID.eq(SysRoleEntityTableDef.SYS_ROLE_ENTITY.ID))
                .where(SysUserEntityTableDef.SYS_USER_ENTITY.ID.eq(id));
        List<SysRoleEntity> roleList = roleMapper.selectListByQuery(roleQuery);
        Set<GrantedAuthority> authorities = new HashSet<>();
        for (SysRoleEntity role : roleList){
            authorities.add((GrantedAuthority) role::getSign);
        }
        return new LoginUser(sysUser.getUname(), sysUser.getPwd(), authorities);
    }
}
